<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="PHP," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="本文内容来自PHP手册

PHP变量PHP 中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。
变量名与 PHP 中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头，后面跟上任意数量的字母，数字，或者下划线。按照正常的正则表达式，它将被表述为：&amp;#39;[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*&amp;#39;。
1Note: $t">
<meta property="og:type" content="article">
<meta property="og:title" content="PHP变量和常量">
<meta property="og:url" content="http://yoursite.com/2017/05/16/PHP变量和常量/index.html">
<meta property="og:site_name" content="EasyBlog">
<meta property="og:description" content="本文内容来自PHP手册

PHP变量PHP 中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。
变量名与 PHP 中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头，后面跟上任意数量的字母，数字，或者下划线。按照正常的正则表达式，它将被表述为：&amp;#39;[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*&amp;#39;。
1Note: $t">
<meta property="og:updated_time" content="2017-05-16T06:23:44.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="PHP变量和常量">
<meta name="twitter:description" content="本文内容来自PHP手册

PHP变量PHP 中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。
变量名与 PHP 中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头，后面跟上任意数量的字母，数字，或者下划线。按照正常的正则表达式，它将被表述为：&amp;#39;[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*&amp;#39;。
1Note: $t">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/05/16/PHP变量和常量/"/>





  <title> PHP变量和常量 | EasyBlog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?07a6d49ae67fe991e0ce3c2f3955e0f9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">EasyBlog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/05/16/PHP变量和常量/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gasbylei">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://gasbylei.github.io/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="EasyBlog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">
            
            
              
                PHP变量和常量
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-16T14:17:49+08:00">
                2017-05-16
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/05/16/PHP变量和常量/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017/05/16/PHP变量和常量/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本文内容来自<a href="http://php.net/manual/zh/language.variables.php" target="_blank" rel="external">PHP手册</a></p>
</blockquote>
<h1 id="PHP变量"><a href="#PHP变量" class="headerlink" title="PHP变量"></a>PHP变量</h1><p>PHP 中的变量用一个美元符号后面跟变量名来表示。<strong>变量名是区分大小写的</strong>。</p>
<p>变量名与 PHP 中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头，后面跟上任意数量的字母，数字，或者下划线。按照正常的正则表达式，它将被表述为：<code>&#39;[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*&#39;</code>。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Note: <span class="keyword">$this</span> 是一个特殊的变量，它不能被赋值。</div></pre></td></tr></table></figure>
<p>变量默认总是<strong>传值赋值</strong>。那也就是说，当将一个表达式的值赋予一个变量时，整个原始表达式的值被赋值到目标变量。这意味着，例如，当一个变量的值赋予另外一个变量时，改变其中一个变量的值，将不会影响到另外一个变量。</p>
<p>PHP 也提供了另外一种方式给变量赋值：引用赋值。这意味着新的变量简单的引用（换言之，“成为其别名” 或者 “指向”）了原始变量。改动新的变量将影响到原始变量，反之亦然。</p>
<p>使用引用赋值，简单地将一个<code>&amp;</code>符号加到将要赋值的变量前（源变量）。例如，下列代码片断将输出“My name is Bob”两次：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$foo = <span class="string">'Bob'</span>;              <span class="comment">// 将 'Bob' 赋给 $foo</span></div><div class="line">$bar = &amp;$foo;              <span class="comment">// 通过 $bar 引用 $foo</span></div><div class="line">$bar = <span class="string">"My name is $bar"</span>;  <span class="comment">// 修改 $bar 变量</span></div><div class="line"><span class="keyword">echo</span> $bar;</div><div class="line"><span class="keyword">echo</span> $foo;                 <span class="comment">// $foo 的值也被修改</span></div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>有一点重要事项必须指出，那就是<strong>只有有名字的变量才可以引用赋值</strong>。</p>
<p>虽然在 PHP 中并不需要初始化变量，但对变量进行初始化是个好习惯。未初始化的变量具有其类型的默认值 - 布尔类型的变量默认值是 FALSE，整形和浮点型变量默认值是零，字符串型变量（例如用于 echo 中）默认值是空字符串以及数组变量的默认值是空数组。</p>
<a id="more"></a>
<h2 id="变量范围"><a href="#变量范围" class="headerlink" title="变量范围"></a>变量范围</h2><p>变量的范围即它定义的上下文背景（也就是它的生效范围）。大部分的 PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了 <code>include</code> 和 <code>require</code> 引入的文件。例如</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$a = <span class="number">1</span>;</div><div class="line"><span class="keyword">include</span> <span class="string">'b.inc'</span>;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>这里变量 <code>$a</code>将会在包含文件<code>b.inc</code>中生效。但是，在用户自定义函数中，一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内。例如：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$a = <span class="number">1</span>; <span class="comment">/* global scope */</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">Test</span><span class="params">()</span></span></div><div class="line">&#123;</div><div class="line">    <span class="keyword">echo</span> $a; <span class="comment">/* reference to local scope variable */</span></div><div class="line">&#125;</div><div class="line"></div><div class="line">Test();</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>这个脚本不会有任何输出，因为 echo 语句引用了一个局部版本的变量<code>$a</code>，而且在这个范围内，它并没有被赋值。你可能注意到 PHP 的全局变量和 C 语言有一点点不同，在 C 语言中，全局变量在函数中自动生效，除非被局部变量覆盖。这可能引起一些问题，有些人可能不小心就改变了一个全局变量。PHP 中全局变量在函数中使用时必须声明为 <code>global</code>。</p>
<h3 id="global-关键字"><a href="#global-关键字" class="headerlink" title="global 关键字"></a>global 关键字</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$a = <span class="number">1</span>;</div><div class="line">$b = <span class="number">2</span>;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">Sum</span><span class="params">()</span></span></div><div class="line">&#123;</div><div class="line">    <span class="keyword">global</span> $a, $b;</div><div class="line"></div><div class="line">    $b = $a + $b;</div><div class="line">&#125;</div><div class="line"></div><div class="line">Sum();</div><div class="line"><span class="keyword">echo</span> $b;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>以上脚本的输出将是“3”。在函数中声明了全局变量 <code>$a</code>和 <code>$b</code>之后，对任一变量的所有引用都会指向其全局版本。对于一个函数能够声明的全局变量的最大个数，PHP 没有限制。</p>
<p>Example #1 使用 <code>$GLOBALS</code> 替代 <code>global</code></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$a = <span class="number">1</span>;</div><div class="line">$b = <span class="number">2</span>;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">Sum</span><span class="params">()</span></span></div><div class="line">&#123;</div><div class="line">    $GLOBALS[<span class="string">'b'</span>] = $GLOBALS[<span class="string">'a'</span>] + $GLOBALS[<span class="string">'b'</span>];</div><div class="line">&#125;</div><div class="line"></div><div class="line">Sum();</div><div class="line"><span class="keyword">echo</span> $b;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p><code>$GLOBALS</code> 是一个关联数组，每一个变量为一个元素，键名对应变量名，值对应变量的内容。<code>$GLOBALS</code> 之所以在全局范围内存在，是因为<code>$GLOBALS</code> 是一个超全局变量。以下范例显示了超全局变量的用处：</p>
<p>Example #2 演示超全局变量和作用域的例子</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">test_global</span><span class="params">()</span></span></div><div class="line">&#123;</div><div class="line">    <span class="comment">// 大多数的预定义变量并不 "super"，它们需要用 'global' 关键字来使它们在函数的本地区域中有效。</span></div><div class="line">    <span class="keyword">global</span> $HTTP_POST_VARS;</div><div class="line"></div><div class="line">    <span class="keyword">echo</span> $HTTP_POST_VARS[<span class="string">'name'</span>];</div><div class="line"></div><div class="line">    <span class="comment">// Superglobals 在任何范围内都有效，它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。</span></div><div class="line">    <span class="keyword">echo</span> $_POST[<span class="string">'name'</span>];</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h3 id="使用静态变量"><a href="#使用静态变量" class="headerlink" title="使用静态变量"></a>使用静态变量</h3><p>变量范围的另一个重要特性是静态变量（static variable）。静态变量仅在局部函数域中存在，但当程序执行离开此作用域时，其值并不丢失。</p>
<p>Example #3 演示需要静态变量的例子</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">Test</span><span class="params">()</span></span></div><div class="line">&#123;</div><div class="line">    $a = <span class="number">0</span>;</div><div class="line">    <span class="keyword">echo</span> $a;</div><div class="line">    $a++;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>本函数没什么用处，因为每次调用时都会将 <code>$a</code> 的值设为 0 并输出 0。将变量加一的 <code>$a++</code> 没有作用，因为一旦退出本函数则变量 <code>$a</code>就不存在了。要写一个不会丢失本次计数值的计数函数，要将变量 <code>$a</code> 定义为静态的：</p>
<p>Example #4 使用静态变量的例子</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span><span class="params">()</span></span></div><div class="line">&#123;</div><div class="line">    <span class="keyword">static</span> $a = <span class="number">0</span>;</div><div class="line">    <span class="keyword">echo</span> $a;</div><div class="line">    $a++;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>现在，变量 <code>$a</code>仅在第一次调用 <code>test()</code>函数时被初始化，之后每次调用 <code>test()</code> 函数都会输出 <code>$a</code> 的值并加一。</p>
<p>静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心，因为可能会无穷递归下去。必须确保有充分的方法来中止递归。以下这个简单的函数递归计数到 10，使用静态变量 <code>$count</code> 来判断何时停止：</p>
<p>Example #5 静态变量与递归函数</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span><span class="params">()</span></span></div><div class="line">&#123;</div><div class="line">    <span class="keyword">static</span> $count = <span class="number">0</span>;</div><div class="line"></div><div class="line">    $count++;</div><div class="line">    <span class="keyword">echo</span> $count;</div><div class="line">    <span class="keyword">if</span> ($count &lt; <span class="number">10</span>) &#123;</div><div class="line">        test();</div><div class="line">    &#125;</div><div class="line">    $count--;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>静态变量可以按照上面的例子声明。如果<strong>在声明中用表达式的结果对其赋值会导致解析错误</strong>。</p>
<p>Example #6 声明静态变量</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span><span class="params">()</span></span>&#123;</div><div class="line">    <span class="keyword">static</span> $int = <span class="number">0</span>;          <span class="comment">// correct</span></div><div class="line">    <span class="keyword">static</span> $int = <span class="number">1</span>+<span class="number">2</span>;        <span class="comment">// wrong  (as it is an expression)</span></div><div class="line">    <span class="keyword">static</span> $int = sqrt(<span class="number">121</span>);  <span class="comment">// wrong  (as it is an expression too)</span></div><div class="line"></div><div class="line">    $int++;</div><div class="line">    <span class="keyword">echo</span> $int;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>静态声明是在编译时解析的。</p>
<h2 id="可变变量"><a href="#可变变量" class="headerlink" title="可变变量"></a>可变变量</h2><p>有时候使用可变变量名是很方便的。就是说，一个变量的变量名可以动态的设置和使用。一个普通的变量通过声明来设置，例如：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$a = <span class="string">'hello'</span>;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>一个可变变量获取了一个普通变量的值作为这个可变变量的变量名。在上面的例子中 hello 使用了两个美元符号（$）以后，就可以作为一个可变变量的变量了。例如：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$$a = <span class="string">'world'</span>;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>这时，两个变量都被定义了：<code>$a</code>的内容是“hello”并且<code>$hello</code>的内容是“world”。因此，以下语句：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="keyword">echo</span> <span class="string">"$a $&#123;$a&#125;"</span>;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>与以下语句输出完全相同的结果</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="keyword">echo</span> <span class="string">"$a $hello"</span>;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>它们都会输出：hello world。</p>
<h1 id="PHP常量"><a href="#PHP常量" class="headerlink" title="PHP常量"></a>PHP常量</h1><p>常量是一个简单值的标识符（名字）。如同其名称所暗示的，在脚本执行期间该值不能改变（除了所谓的魔术常量，它们其实不是常量）。常量默认为大小写敏感。传统上常量标识符总是大写的。</p>
<h3 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h3><p>可以用 <code>define()</code> 函数来定义常量，在 PHP 5.3.0 以后，可以使用 <code>const</code> 关键字在类定义之外定义常量。一个常量一旦被定义，就不能再改变或者取消定义。</p>
<p>常量只能包含标量数据（<code>boolean</code>，<code>integer</code>，<code>float</code> 和 <code>string</code>）。可以定义 <code>resource</code> 常量，但应尽量避免，因为会造成不可预料的结果。</p>
<p>可以简单的通过指定其名字来取得常量的值，与变量不同，不应该在常量前面加上 $ 符号。如果常量名是动态的，也可以用函数<code>constant()</code>来获取常量的值。用 <code>get_defined_constants()</code> 可以获得所有已定义的常量列表。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Note: 常量和（全局）变量在不同的名字空间中。这意味着例如 TRUE 和 $TRUE 是不同的。</div></pre></td></tr></table></figure>
<p>如果使用了一个未定义的常量，PHP 假定想要的是该常量本身的名字，如同用字符串调用它一样（CONSTANT 对应 “CONSTANT”）。此时将发出一个 E_NOTICE 级的错误。参见手册中为什么 <code>$foo[bar]</code> 是错误的（除非事先用 <code>define()</code> 将 bar 定义为一个常量）。如果只想检查是否定义了某常量，用 <code>defined()</code> 函数。</p>
<p>常量和变量有如下不同：</p>
<ul>
<li>常量前面没有美元符号（$）；</li>
<li>常量只能用 define() 函数定义，而不能通过赋值语句；</li>
<li>常量可以不用理会变量的作用域而在任何地方定义和访问；</li>
<li>常量一旦定义就不能被重新定义或者取消定义；</li>
<li>常量的值只能是标量。</li>
</ul>
<p>Example #1 定义常量</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">define(<span class="string">"CONSTANT"</span>, <span class="string">"Hello world."</span>);</div><div class="line"><span class="keyword">echo</span> CONSTANT; <span class="comment">// outputs "Hello world."</span></div><div class="line"><span class="keyword">echo</span> Constant; <span class="comment">// 输出 "Constant" 并发出一个提示级别错误信息</span></div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<p>Example #2 使用关键字 const 定义常量</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="comment">// 以下代码在 PHP 5.3.0 后可以正常工作</span></div><div class="line"><span class="keyword">const</span> CONSTANT = <span class="string">'Hello World'</span>;</div><div class="line"></div><div class="line"><span class="keyword">echo</span> CONSTANT;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Note:</div><div class="line">和使用 define() 来定义常量相反的是，使用 const 关键字定义常量必须处于最顶端的作用区域，因为用此方法是在编译时定义的。这就意味着不能在函数内，循环内以及 if 语句之内用 const 来定义常量。</div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/PHP/" rel="tag"># PHP</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/05/15/PHP类型-下篇/" rel="next" title="PHP类型(下篇)">
                <i class="fa fa-chevron-left"></i> PHP类型(下篇)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/05/16/PHP运算符/" rel="prev" title="PHP运算符">
                PHP运算符 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://gasbylei.github.io/uploads/avatar.png"
               alt="Gasbylei" />
          <p class="site-author-name" itemprop="name">Gasbylei</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">17</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/Gasbylei" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#PHP变量"><span class="nav-number">1.</span> <span class="nav-text">PHP变量</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#变量范围"><span class="nav-number">1.1.</span> <span class="nav-text">变量范围</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#global-关键字"><span class="nav-number">1.1.1.</span> <span class="nav-text">global 关键字</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用静态变量"><span class="nav-number">1.1.2.</span> <span class="nav-text">使用静态变量</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#可变变量"><span class="nav-number">1.2.</span> <span class="nav-text">可变变量</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#PHP常量"><span class="nav-number">2.</span> <span class="nav-text">PHP常量</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法"><span class="nav-number">2.0.1.</span> <span class="nav-text">语法</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gasbylei</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'gatsbylei';
      var disqus_identifier = '2017/05/16/PHP变量和常量/';

      var disqus_title = "PHP变量和常量";


      function run_disqus_script(disqus_script) {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');

      
        var disqus_config = function () {
            this.page.url = disqus_url;
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
        };
        run_disqus_script('embed.js');
      

    </script>
  










  
  

  

  

  

  


  

</body>
</html>
